
package com.vision.bigDataApi.config;

        import com.vision.bigDataApi.enums.ReturnStatus;
        import com.vision.bigDataApi.service.common.ResultService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.web.bind.annotation.ControllerAdvice;
        import org.springframework.web.bind.annotation.ExceptionHandler;
        import org.springframework.web.bind.annotation.ResponseBody;

        import javax.validation.ConstraintViolation;
        import javax.validation.ConstraintViolationException;
        import java.util.*;

@ControllerAdvice
public class MyExceptionHandler {




    @Autowired
    private ResultService resultService;

    @ExceptionHandler(value = ConstraintViolationException.class) // 方法级别参数使用校验注解不满足条件时会报这个错
    @ResponseBody
    public String constraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }

        return resultService.result(ReturnStatus.FAILURE, msgList, "参数验证不合法",null);
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 500);
        map.put("msg", "服务器异常");
        return map;
    }

}

